<template>
  <a-modal
    v-model:open="openAddUser"
    title="新增用户"
    ok-text="保存"
    cancel-text="取消"
    @ok="addUser"
  >
    <a-form layout="horizontal" :model="addUserParam" style="max-width: 600px">
      <a-form-item label="用户昵称">
        <a-input v-model:value="addUserParam.userName" placeholder="输入昵称" allow-clear />
      </a-form-item>
      <a-form-item label="用户账号">
        <a-input
          v-model:value="addUserParam.userAccount"
          placeholder="输入账号"
          allow-clear
        />
      </a-form-item>

      <!--上传头像组件-->
      <a-form-item label="用户头像">
        <PictureUpload :picture="picture" :user-avatar="true" :on-success="onSuccess"/>
      </a-form-item>

      <a-form-item label="用户简介">
        <a-textarea :rows="4" v-model:value="addUserParam.userProfile" />
      </a-form-item>

      <a-form-item label="用户权限">
        <a-radio-group v-model:value="addUserParam.userRole">
          <a-radio value="user">普通用户</a-radio>
          <a-radio value="admin">管理员</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">

import { PlusOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'
import { addUserUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import PictureUpload from '@/components/PictureUpload.vue'


// 头像上传所需变量
const picture = ref<API.PictureVO>({})

const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  addUserParam.value.userAvatar = newPicture.url
}


const openAddUser = ref(false)
let addUserParam = ref<API.UserAddRequest>({})
// 获取父组件方法
const emit = defineEmits(['refresh'])

// 打开对话框
const openDialog = () => {
  addUserParam.value = {
    userAccount: '',
    userName: '',
    userProfile: '',
    userAvatar: '',
    userRole: 'user',
  }
  openAddUser.value = true
}

// 添加用户
const addUser = async () => {
  const res = await addUserUsingPost(addUserParam.value)
  if (res.data.code === 0 && res.data.data) {
    addUserParam.value = {
      userAccount: '',
      userName: '',
      userProfile: '',
      userAvatar: '',
      userRole: 'user',
    }
    openAddUser.value = false
    message.success('添加成功')
    await emit('refresh')
  } else {
    message.error('添加失败，' + res.data.message)
  }
  openAddUser.value = false
}

// 暴露方法给父组件
defineExpose({
  openDialog
});

</script>

<style scoped>

#picture-upload :deep(.ant-upload) {
  width: 100px;
  height: 100px;
  max-width: 152px;
  max-height: 152px;
  overflow: hidden;
}

#picture-upload img {
  max-width: 152px;
  max-height: 152px;
}


</style>
